import { DragBeginEvent, DragEndEvent } from "../event/DragEvent"
import MeasurementInput from "../mesh/MeasurementInput"
import InputIniModule, { InputSubscription } from "../module/InputIniModule"
import Comparator from "../utils/Comparator"
import Ne from "../packages/76870"
import Grouper from "../utils/Grouper"
import SnappablePointer from "./SnappablePointer"
import MeasurementModeModule from "../module/MeasurementModeModule"
export default class MeasurementJointEditor {
  points: Grouper
  pointer: SnappablePointer
  getPhase: MeasurementModeModule["getPhase"]
  onDrag: MeasurementModeModule["onEdit"]
  onDragEnd: MeasurementModeModule["onEditEnd"]
  inputSubscriptions: InputSubscription[]
  onDragBegin: (_e: any, _t: any, i: any) => boolean
  onDragEndEvent: () => boolean
  onDragEvent: (e: any, _t: any, i: any) => boolean
  constructor(e, t: InputIniModule, i, s, n, r) {
    this.points = e
    this.pointer = i
    this.getPhase = s
    this.onDrag = n
    this.onDragEnd = r
    this.inputSubscriptions = []
    this.onDragBegin = (_e, _t, i) => {
      if (!i || void 0 === i.index) return !1
      const s = this.points.isStartIndex(i.index) ? i.index + 1 : i.index - 1,
        n = this.points.get(s)
      this.pointer.clearOrigin()
      this.pointer.setOriginFromPointer(n)
      return !0
    }
    this.onDragEndEvent = () => (this.onDragEnd(), this.pointer.clearOrigin(), !0)
    this.onDragEvent = (e, _t, i) => {
      if (e.buttons !== Ne.r3.PRIMARY) return !1
      if (!i || void 0 === i.index || void 0 === i.instanceId) return !1
      const s = this.pointer.getIntersection()
      s && this.points.update(i.index, s.point)
      this.onDrag(i.instanceId)
      return !0
    }
    this.inputSubscriptions.push(
      t.registerMeshHandler(DragBeginEvent, Comparator.isType(MeasurementInput), this.onDragBegin),
      t.registerMeshHandler(DragEvent, Comparator.isType(MeasurementInput), this.onDragEvent),
      t.registerMeshHandler(DragEndEvent, Comparator.isType(MeasurementInput), this.onDragEndEvent)
    )
    this.deactivate()
  }
  activate() {
    for (const e of this.inputSubscriptions) e.renew()
  }
  deactivate() {
    for (const e of this.inputSubscriptions) e.cancel()
  }
}
